var http = require('http');
var URL = require('url');
module.exports = {
    youku:function (uri, callback) {
        var id = uri.match(/id_(.*).html/)[1];
        var n = 0;
        var ret = {
            type:'youku',
            vid:id,
            imgWidth:448,
            imgHeight:336
        };
        var options = URL.parse('http://v.youku.com/player/getPlayList/VideoIDS/' + id);
        http.get(options, function (res) {
            var str = '';
            res.on('data', function (data) {
                str += data.toString();
            });
            res.on('end', function () {
                var data = JSON.parse(str).data[0];
                ret.title = data.title;
                ret.ts = data.ts;
                ret.videoid = data.videoid;
                /** @namespace data.logo */
                ret.img = data.logo;
                ret.tags = data.tags;
                if (++n == 2) {
                    callback(ret);
                }
            });
        });
        http.get(URL.parse(uri), function (res) {
            var str = '';
            res.on('data', function (data) {
                str += data.toString();
            });
            res.on('end', function () {
                var description = str.match(/<meta name="description" content="([^"]*)/)[1];
                ret.description = description.replace(/\n/g, ' ');
                if (++n == 2) {
                    callback(ret);
                }
            });
        });
    },
    tudou:function (uri, callback) {
        //http://www.tudou.com/v/89aZgkIuZWw/&resourceId=0_04_05_99/v.swf
        //http://www.tudou.com/programs/view/89aZgkIuZWw
        //http://www.tudou.com/listplay/EoWxiLVsQcw/GOFrPBJcdJc.html
        var url = 'http://www.tudou.com/v/id/&resourceId=0_04_05_99/v.swf';
        var url2 = 'http://www.tudou.com/programs/view/';
        var arr, id , n = 0;
        if (uri.indexOf('listplay') > -1) {
            arr = uri.match(/[A-Za-z]+\/[A-Za-z]+\/[A-Za-z]+\/(.*).html/);
        } else {
            arr = uri.match(/view\/(.*)/);
        }
        id = arr ? arr[1] : arr;
        var ret = {
            type:'tudou',
            vid:id,
            imgWidth:320,
            imgHeight:240
        };
        http.get(URL.parse(url.replace('id', id)), function (res) {
            var obj = {};
            var str = res.headers.location.split('?')[1];
            str.split('&').forEach(function (item) {
                item = item.split('=');
                obj[item[0]] = decodeURIComponent(item[1]);
            });
            ret.title = obj.title;
            ret.img = obj.snap_pic;
            ret.tag = obj.tag.split(',');
            ret.description = obj.description || '';
            /** @namespace obj.iid */
            ret.vid = obj.iid;
            callback(ret);
        });
    }
};